package com.lap.context.starter.core.interceptor;

import com.lap.context.starter.entity.LocalInfo;
import com.lap.context.starter.handler.LangHandler;
import com.lap.context.starter.shared.Constant;
import com.lap.context.starter.shared.LangEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NonNull;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

public class LangInterceptor implements HandlerInterceptor {

  @Override
  public boolean preHandle(
      @NonNull HttpServletRequest request,
      @NonNull HttpServletResponse response,
      @NonNull Object handler) {
    String newLocale =
        StringUtils.defaultIfBlank(
            request.getParameter(Constant.LANG), request.getHeader(Constant.LANG));

    LangEnum lang = LangEnum.getStoreCode(newLocale);
    LangHandler.set(new LocalInfo(lang.getLang(), lang.getStoreLang()));
    return true;
  }

  @Override
  public void afterCompletion(
      @NonNull HttpServletRequest request,
      @NonNull HttpServletResponse response,
      @NonNull Object handler,
      Exception ex) {
    LangHandler.remove();
  }
}
